<template>
  <div class="home">
    <el-row :gutter="20" class="home-box">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.articleTotal }}</div>
            <div class="stat-label">文章总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.userTotal }}</div>
            <div class="stat-label">用户总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.totalViews }}</div>
            <div class="stat-label">总浏览量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.publishedCount }}</div>
            <div class="stat-label">已发布文章</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="home-box">
      <el-col :span="12">
        <el-card shadow="hover">
          <div ref="barElement" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div ref="categoryBarElement" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="home-box">
      <el-col :span="12">
        <el-card shadow="hover">
          <div ref="lineElement" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div ref="pieElement" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getStatistics, listCate } from '../api/index'

export default {
  data() {
    return {
      statistics: {
        articleTotal: 0,
        userTotal: 0,
        totalViews: 0,
        publishedCount: 0,
        articleByCate: [],
        userByGender: [],
        viewsByCate: []
      },
      categoryList: [],
      charts: {
        bar: null,
        pie: null,
        line: null,
        categoryBar: null
      }
    }
  },
  computed: {
    categoryNames() {
      const categories = new Set()
      this.categoryList.forEach(item => {
        if (item.cate) {
          categories.add(item.cate)
        }
      })
      return Array.from(categories)
    }
  },
  mounted() {
    this.initData()
    this.$root.$on('refresh-home-data', this.initData)
  },
  beforeDestroy() {
    this.$root.$off('refresh-home-data', this.initData)
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
  },
  methods: {
    async initData() {
      await this.loadCategories()
      await this.getStatisticsData()
    },
    async loadCategories() {
      try {
        const resData = await listCate()
        if (resData && resData.code === 200) {
          this.categoryList = resData.result || []
        } else {
          console.error('加载分类列表失败:', resData.msg)
        }
      } catch (error) {
        console.error('加载分类列表失败:', error)
      }
    },
    async getStatisticsData() {
      let token = localStorage.getItem("AUTO_TOKEN")
      if (token) {
        await getStatistics({ token })
          .then(resData => {
            if (resData.code == 200) {
              this.statistics = {
                articleTotal: resData.data.articleTotal,
                userTotal: resData.data.userTotal,
                totalViews: resData.data.totalViews,
                publishedCount: resData.data.publishedCount || 0,
                articleByCate: resData.data.articleByCate || [],
                userByGender: resData.data.userByGender || [],
                viewsByCate: resData.data.viewsByCate || []
              }
              this.$nextTick(() => {
                this.initBarChart()
                this.initPieChart()
                this.initLineChart()
                this.initCategoryBarChart()
              })
            }
          })
          .catch(err => {
            console.error('获取统计数据失败:', err)
          })
      }
    },
    initBarChart() {
      let barElement = this.$refs.barElement
      if (barElement) {
        if (this.charts.bar) {
          this.charts.bar.dispose()
        }
        var myChart = echarts.init(barElement)
        this.charts.bar = myChart

        const cateNames = this.categoryNames
        const cateData = {}
        cateNames.forEach(name => {
          cateData[name] = 0
        })

        this.statistics.articleByCate.forEach(item => {
          if (Object.prototype.hasOwnProperty.call(cateData, item.cate)) {
            cateData[item.cate] = item.count
          }
        })

        myChart.setOption({
          title: {
            text: '文章数量统计',
            left: 'center'
          },
          tooltip: {},
          xAxis: {
            data: cateNames
          },
          yAxis: {},
          series: [
            {
              name: '数量',
              type: 'bar',
              data: cateNames.map(name => cateData[name]),
              itemStyle: {
                color: '#a0d8ef'
              }
            }
          ]
        })
      }
    },
    initPieChart() {
      let pieElement = this.$refs.pieElement
      if (pieElement) {
        if (this.charts.pie) {
          this.charts.pie.dispose()
        }
        var myChart2 = echarts.init(pieElement)
        this.charts.pie = myChart2

        const pieData = this.statistics.userByGender.map(item => ({
          value: item.count,
          name: item.gender
        }))

        if (pieData.length === 0) {
          pieData.push(
            { value: 0, name: '男生' },
            { value: 0, name: '女生' },
            { value: 0, name: '未知性别' }
          )
        }

        myChart2.setOption({
          title: {
            text: '按性别统计用户',
            left: 'center'
          },
          series: [
            {
              type: 'pie',
              data: pieData,
              radius: '50%'
            }
          ]
        })
      }
    },
    initLineChart() {
      let lineElement = this.$refs.lineElement
      if (lineElement) {
        if (this.charts.line) {
          this.charts.line.dispose()
        }
        var myChart3 = echarts.init(lineElement)
        this.charts.line = myChart3

        const cateNames = this.categoryNames
        const viewsData = {}
        cateNames.forEach(name => {
          viewsData[name] = 0
        })

        this.statistics.viewsByCate.forEach(item => {
          if (Object.prototype.hasOwnProperty.call(viewsData, item.cate)) {
            viewsData[item.cate] = item.views || 0
          }
        })

        myChart3.setOption({
          title: {
            text: '不同分类的浏览量统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: '{b}: {c}'
          },
          xAxis: {
            type: 'category',
            data: cateNames,
            boundaryGap: false
          },
          yAxis: {
            type: 'value',
            name: '浏览量'
          },
          series: [
            {
              name: '浏览量',
              type: 'line',
              data: cateNames.map(name => viewsData[name]),
              itemStyle: {
                color: '#a0d8ef'
              },
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: 'rgba(160, 216, 239, 0.3)' },
                    { offset: 1, color: 'rgba(160, 216, 239, 0.1)' }
                  ]
                }
              }
            }
          ]
        })
      }
    },
    initCategoryBarChart() {
      let categoryBarElement = this.$refs.categoryBarElement
      if (categoryBarElement) {
        if (this.charts.categoryBar) {
          this.charts.categoryBar.dispose()
        }
        var myChart = echarts.init(categoryBarElement)
        this.charts.categoryBar = myChart

        const categoryCount = {}
        if (this.categoryList && this.categoryList.length > 0) {
          this.categoryList.forEach(item => {
            if (item.cate) {
              if (!categoryCount[item.cate]) {
                categoryCount[item.cate] = 0
              }
              categoryCount[item.cate]++
            }
          })
        }

        const categories = Object.keys(categoryCount)
        const counts = categories.map(cate => categoryCount[cate])

        myChart.setOption({
          title: {
            text: '各一级导航下二级导航数量',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: '{b}: {c}个'
          },
          grid: {
            left: '15%',
            right: '10%',
            top: '15%',
            bottom: '10%'
          },
          xAxis: {
            type: 'value',
            name: '数量',
            nameLocation: 'middle',
            nameGap: 30
          },
          yAxis: {
            type: 'category',
            data: categories,
            axisLabel: {
              interval: 0
            }
          },
          series: [
            {
              name: '二级导航数量',
              type: 'bar',
              data: counts,
              itemStyle: {
                color: '#a0d8ef'
              },
              label: {
                show: true,
                position: 'right',
                formatter: '{c}'
              }
            }
          ]
        })
      }
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(newRoute) {
        this.$store.commit("addTab", newRoute)
      }
    }
  }
}
</script>

<style scoped lang="less">
.home {
  .home-box {
    padding: 20px 0;
  }

  .stat-card {
    text-align: center;

    .stat-item {
      padding: 20px 0;

      .stat-value {
        font-size: 36px;
        font-weight: bold;
        color: #a0d8ef;
        margin-bottom: 10px;
      }

      .stat-label {
        font-size: 14px;
        color: #606266;
      }
    }
  }
}
</style>
